const axios = require('axios');
const cheerio = require('cheerio');
const CryptoJS = require('crypto-js');

// 加载书源配置
const bookSource = {
  // 从你的JSON中提取关键规则（已简化）
  bookSourceUrl: "http://manwaso.cc",
  ruleSearchUrl: "http://manwaso.cc/search?keyword=searchKey",
  ruleSearchList: ".manga-list li, .book-list li",
  ruleSearchName: "tag.p@text, .book-list-info-title@text",
  ruleSearchNoteUrl: "tag.a.0@href",
  ruleCoverUrl: ".detail-main-cover img@data-original",
  ruleChapterList: "id.detail-list-select@tag.a",
  ruleBookContent: "@css:#cp_img img@data-r-src",
  ruleBookContentDecoder: {
    iv: "my2ecret782ecret",
    key: "my2ecret782ecret",
    bm: "UTF-8",
    mode: "AES/CBC/PKCS5Padding"
  }
};

class ComicScraper {
  constructor() {
    this.baseUrl = bookSource.bookSourceUrl;
    this.axios = axios.create({
      headers: {
        "User-Agent": "Mozilla/5.0 (Linux; Android 10; HarmonyOS; PCT-AL10; HMSCore 6.5.0.312; GMSCore 20.15.16) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.105 HuaweiBrowser/12.1.0.302 Mobile Safari/537.36",
        "Referer": this.baseUrl
      },
      timeout: 5000 // 5秒超时
    });
  }
  /**
     * 搜索漫画
     * @param {string} keyword - 搜索关键词
     * @returns {Promise<Array<{name: string, url: string, cover: string}>>}
     */
  // 搜索漫画
  async searchComics(keyword) {
    if (!keyword || typeof keyword !== 'string') {
      throw new Error('Invalid keyword: must be a non-empty string');
    }
    try {
      const url = `${this.baseUrl}/search?keyword=${encodeURIComponent(keyword)}`;
      const response = await this.axios.get(url);
      const $ = cheerio.load(response.data);

      const comics = [];
      $('.manga-list li, .book-list li').each((i, el) => {
        const $el = $(el);

        // 提取数据（保留你的原始选择器）
        const name = $el.find('.title, .book-list-info-title').text().trim();
        const relativeUrl = $el.find('a').attr('href');
        const cover = $el.find('.manga-list-2-cover-img').attr('src') ||
          $el.find('.book-list-cover-img').attr('data-original');

        if (name && relativeUrl) {
          comics.push({
            name,
            url: this.baseUrl + relativeUrl,
            cover: cover || null // 如果没有封面则返回null
          });
        }
      });
      return comics;
    } catch (error) {
      throw new Error(`搜索失败: ${error.message}`);
    }

  }

  // 获取章节列表
  async getChapters(comicUrl) {
    try {
      // 1. 发送请求
      const response = await this.axios.get(comicUrl);
      const $ = cheerio.load(response.data);

      // 2. 解析章节列表
      const chapters = [];
      $('#detail-list-select li a.chapteritem').each((i, el) => {
        const $el = $(el);
        chapters.push({
          name: $el.attr('title') || $el.text().trim(), // 优先使用title属性
          url: this.baseUrl + $el.attr('href')
        });
      });

      // 3. 按原始顺序返回（如需倒序则添加.reverse()）
      return chapters;
    } catch (error) {
      throw new Error(`无法加载章节列表: ${error.message}`);
    }
  }

  // 解密图片链接 (AES/CBC/PKCS5Padding)
  decryptImage(encryptedData) {
    const { key, iv, mode, bm } = bookSource.ruleBookContentDecoder;

    // 1. 检查是否是Base64（可能已经是解密后的URL）
    if (!encryptedData.startsWith('http') && !encryptedData.includes('=')) {
      try {
        // 尝试直接解密（非Base64数据）
        const decrypted = CryptoJS.AES.decrypt(
          { ciphertext: CryptoJS.enc.Hex.parse(encryptedData) },
          CryptoJS.enc.Utf8.parse(key),
          {
            iv: CryptoJS.enc.Utf8.parse(iv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
          }
        );
        return decrypted.toString(CryptoJS.enc.Utf8);
      } catch (e) {
        console.warn('AES解密失败，尝试直接返回:', encryptedData);
        return encryptedData; // 可能已经是明文URL
      }
    }

    // 2. 标准Base64解密
    const decrypted = CryptoJS.AES.decrypt(
      encryptedData,
      CryptoJS.enc.Utf8.parse(key),
      {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
  }

  // 获取章节图片
  async getImages(chapterUrl) {
    try {
      const response = await this.axios.get(chapterUrl);
      const $ = cheerio.load(response.data);

      const images = [];
      $('#cp_img img').each((i, el) => {
        const imgUrl = $(el).attr('data-r-src') || $(el).attr('src');

        // 排除"missing6-m1.png"等提示图片
        if (imgUrl && !imgUrl.includes('missing6-m1.png')) {
          images.push(imgUrl);
        }
      });

      return images;
    } catch (error) {
      throw new Error(`获取图片失败: ${error.message}`);
    }
  }
}

module.exports = new ComicScraper();